<template>
  <div class="container">
    <img :src="`${RESOURCE}/img/banner.png`" class="banner">
    <div class="login" v-if="!userInfo">
      <input v-model="loginForm.mobile" id="mobile" type="tel" placeholder="手机号" maxlength="11">
      <input v-model="loginForm.code" id="code" type="tel" placeholder="验证码" maxlength="4">
      <div id="getCode" @click="getCode" :disabled="disableCodeBtn">{{countdown | codeBtnText}}</div>
    </div>
    <div class="user-info" v-if="userInfo">
      <img :src="userInfo.headerSmall || `${RESOURCE}/img/avatar.png?v=${VERSION}`" class="avatar" onerror="this.src=`${RESOURCE}/img/avatar.png?v=${VERSION}`">
      <div class="nickname">{{userInfo.nickname}}</div>
      <div class="switch-account">切换账号</div>
    </div>
    <div class="product-info">
      <div class="person">1V1</div>
      <div class="title">久趣英语1对1精英外教课</div>
      <div class="info-list">
        <div class="info">北美精英外教在线授课</div>
        <div class="info">固定老师+固定时间</div>
        <div class="info">班主任全程跟踪教学服务</div>
        <div class="info">0销售打扰</div>
        <div class="info">180天退款无忧</div>
        <div class="info">课时有效期一年</div>
      </div>
    </div>
    <div class="buy-bottom-bar">
      <div class="price-info">
        <span class="price">¥ <span class="big">4500</span></span>/60节
      </div>
      <div class="buy" @click="buy">立即付款</div>
    </div>
  </div>
</template>

<script>
  utils.recoverUrlParam()
  utils.initAnalytics('order')
  analytics.send({
    event: `${av}_open`,
    attr: {
      _c: utils.getUrlParam('_c')
    }
  })
  const account = new Account()
  utils.initWechatShare({
    title: '【Qkids久趣】4-12岁，在家跟北美外教学英语，新用户100元体验！',
    desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
    link: `${window.location.protocol}//${window.location.host}/wx`,
    imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png'
  })
  utils.supportPromise(account)
  export default {
    name: 'Order',
    data () {
      return {
        userInfo: null,
        countdown: 60,
        loginForm: {
          mobile: '',
          code: ''
        }
      }
    },
    computed: {
      disableCodeBtn () {
        return this.loginForm.mobile.length === 11 && this.countdown === 60 ? false : true
      }
    },
    filters: {
      codeBtnText (countdown) {
        return countdown === 60 ? '获取验证码' : `重新发送(${countdown}s)`
      }
    },
    async mounted () {
      console.log('test')
      if (utils.isWeChat() && !utils.getUrlParam('code')) account._getWechatAccess()
      this.userInfo = await account.$getUserInfo()
      console.log(this.userInfo)
    },
    methods: {
      // 点击发送验证码
      getCode () {
        const {mobile} = this.loginForm
        if (mobile.length === 11 && /^[0-9]*$/.test(mobile)) {
          if (this.countdown === 60) this.sendCode(mobile)
        } else {
          utils.toast('手机号码格式错误')
        }
      },
      // 发送验证码
      async sendCode (mobile) {
        try {
          await account.$ajax({
            auth: false,
            type: 'POST',
            path: '/s/user/sms/login',
            data: {mobile}
          })
          this.setTime()
          utils.toast('验证码已经发送')
        } catch (err) {
          utils.toast(err.message ? err.message : err)
        }
      },
      // 设置验证码倒计时
      setTime () {
        if (this.countdown > 0) {
          this.countdown--
          setTimeout(this.setTime, 1000)
        } else {
          this.countdown = 60
        }
      },
      // 点击立即付款按钮
      async buy () {
        analytics.send({
          event: `${av}-buy-click`,
          attr: {
            pid: utils.getUrlParam('pid'),
            _c: utils.getUrlParam('_c')
          }
        })
        try {
          if (!this.userInfo) {
            const {mobile, code} = this.loginForm
            if (mobile.length !== 11 || !/^[0-9]*$/.test(mobile)) throw Error('手机号码格式错误')
            if (code.length !== 4 || !/^[0-9]*$/.test(code)) throw Error('验证码格式错误')
            await this.login(mobile, code, this.checkProductInfo)
          } else {
            await this.checkProductInfo()
          }
        } catch (e) {
          utils.toast(err.message ? err.message : err)
        }
      },
      // 检查产品信息
      async checkProductInfo () {
        try {
          const {totalSoldCount, totalLimit} = await account.$ajax({
            type: 'GET',
            path: `/s/products/${utils.getUrlParam('pid')}`
          })
          if (totalLimit === 0 || totalSoldCount <= totalLimit) {
            await this.submitOrder()
          } else {
            utils.toast('本次名额已抢完')
          }
        } catch (err) {
          utils.toast(err.message ? err.message : err)
        }
      },
      // 登录接口
      async login (mobile, smsCode, callback) {
        try {
          const token = await account.$ajax({
            auth: false,
            type: 'POST',
            path: '/s/user/login/sms',
            data: {
              mobile,
              smsCode,
              channel: utils.getUrlParam('_c')
            }
          })
          account._saveToken(token)
          this.countdown = 0
          this.userInfo = await account.$getUserInfo()
          if (utils.isWeChat()) {
            const socialInfo = await account.$ajax({
              type: 'POST',
              path: '/s/user/social',
              data: {
                socialType: 'wx-jqfx',
                socialCode: utils.getUrlParam('code')
              }
            })
            account.socialBinded = true
            account._saveOpenId(socialInfo.socialId)
            callback()
          } else {
            callback()
          }
        } catch (err) {
          utils.toast(err.message ? err.message : err)
        }
      },
      // 下单接口
      async submitOrder () {
        const productId = utils.getUrlParam('pid')
        const verifyUrl = `${window.location.protocol}//${window.location.host}/wx/verify${Math.ceil(Math.random() * 100)}?pid=${utils.getUrlParam('pid')}&_c=${utils.getUrlParam('_c')}`
        try {
          if (utils.getUrlParam('_c').indexOf('invite-one') > -1) {
            const inviteInfo = await account.$ajax({
              type: 'GET',
              path: `/s/events/inviteOneOnOne/code?code=${utils.getUrlParam('rid')}`
            })
            if (inviteInfo.status === 1) {
              utils.toast('福利已被抢完')
              return
            }
            if (inviteInfo.status === 2) {
              utils.toast('福利已过期')
              return
            }
            if (inviteInfo.status === 3) {
              utils.toast('您已领取过福利')
              return
            }
          }
          const bills = await account.$ajax({
            type: 'POST',
            path: '/s/bills',
            data: {
              productId,
              openId: window.localStorage.getItem('QKidsOpenId') || '',
              payChannel: utils.isWeChat() ? 'weixin' : 'alipay',
              returnUrl: verifyUrl,
              tradeType: 'JSAPI',
            }
          })
          if (!bills) window.location.href = verifyUrl
          let {bill_id, status, url, jsApiParameters} = bills
          if (status !== 'error') {
            if (status === 'success' && (!bill_id || !url || !jsApiParameters)) {
              window.location.href = verifyUrl
            } else if (utils.isWeChat()) {
              jsApiParameters = JSON.parse(jsApiParameters)
              jsApiParameters.redirect = verifyUrl
              wxconfig.pay(bill_id, productId, jsApiParameters)
            } else {
              window.location.href = url
            }
          } else {
            utils.toast('下单失败，请重试')
          }
        } catch (err) {
          utils.toast(err.message ? err.message : err)
        }
      }
    }
  }
</script>